//
//  DYTableViewCell.swift
//  DynamicStateLJZ
//
//  Created by kys-11 on 2019/4/9.
//  Copyright © 2019年 xl123. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
@objc protocol clickLonginDelegate: NSObjectProtocol{
    
    func JumpPictureDetailsCell(vc:ImgCollectionViewController)
    
}//代理定义
class DYTableViewCell: UITableViewCell,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout  {
//
//    fileprivate lazy var modalDelegate: ModalAnimationDelegate = ModalAnimationDelegate()
    
    var headimage: UIImageView!
    var namelable:UILabel!
    var contentLable:UILabel!
    var imageCollection:UICollectionView!
    var collectionContainer: UIView!
    var timelable:UILabel!
    var attention:UIButton!//关注
    var likebutton:UIButton!//点赞
    var collectbutton:UIButton!//收藏
    var transmitbutton:UIButton!//转发
    var images:[String] = []
    var imagedetails:[UIImage] = []//
    var layoutsize:CGSize!
    var layoutInsets:UIEdgeInsets!
    var tiao:clickLonginDelegate!
    var Selectedbool:Bool!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style:style,reuseIdentifier:reuseIdentifier)
        if !self.isEqual(nil) {
            
            self.layer.masksToBounds = true
            self.layer.cornerRadius = 20
            //设置圆角
            creat()//实现布局
        }
    }
    
    //重写tabviewcell的大小
    override var frame: CGRect{
//        didSet{
//
//            var newframe = frame
//
//            newframe.origin.x += 9;
//            newframe.origin.y += 9;
//            newframe.size.height -= 9;
//            newframe.size.width -= 18;
//            super.frame = newframe
//        }

        get{
            return super.frame
        }
        set{
                        var newframe = newValue

//                        newframe.origin.x += 9;
                        newframe.origin.y += 9;
                        newframe.size.height -= 9;
//                        newframe.size.width -= 18;
                        super.frame = newframe
        }
    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func reloadData(imagea:[String]) {
        //保存图片数据
       self.images = imagea
       //重新加载数据
        self.imageCollection.reloadData()

        imageCollection.layoutIfNeeded()
        
        let contentheight = self.imageCollection.contentSize.height
        
        print(contentheight)
        
        imageCollection.snp.makeConstraints { (make) in
            make.height.equalTo(contentheight)
        }
     
        contentLable.frame = CGRect(x: 10, y: 63, width: 350, height: getLabHeigh(labelStr: contentLable.text!, font: contentLable.font, width: 327, lineSpacing: 0))//根据内容改变内容lable的大小
    }
    

    func creat(){
        
        headimage = UIImageView()
        self.addSubview(headimage)
        //设置弧度
        headimage.image = UIImage(named: "headimage2.jpg")
        headimage.layer.masksToBounds = true
        headimage.layer.cornerRadius = 20
        headimage.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(10)
            make.height.width.equalTo(40)
        }
        
        namelable = UILabel()
        self.addSubview(namelable)
        namelable.font = UIFont.italicSystemFont(ofSize: 16)
//  namelable.textColor = UIColor.blue
        namelable.text = "某学生"
       namelable.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo((headimage.snp.right)).offset(10)
            make.height.equalTo(20)
        }
        
        timelable = UILabel()
        self.addSubview(timelable)
        timelable.text = "2017-03-23"
        timelable.font = UIFont.italicSystemFont(ofSize: 12)//设置字体大小
        timelable.textColor = UIColor(red: 132/255, green: 132/255, blue: 132/255, alpha: 1)
//  timelable.textColor = UIColor.black
        timelable.snp.makeConstraints { (make) in
            make.top.equalTo(namelable.snp.bottom).offset(4)
            make.left.equalTo(namelable)
            make.height.equalTo(namelable)
        }
        
    
        contentLable = UILabel()
        contentLable.numberOfLines = 0//显示行数
        contentLable.font = UIFont(name: "Heiti SC", size: 14)
        contentLable.textAlignment = .left
//        contentLable.font= UIFont.Weight.bold
        self.addSubview(contentLable)
        
//  contentLable.snp.makeConstraints { (make) in
//  make.top.equalTo(timelable.snp.bottom).offset(10)
//  make.left.equalTo(self).offset(10)
//  make.right.equalTo(self).offset(-10)
//
//  } //发布内容lable的自动布局实现因为修改了cell 的frame后出现了lable内容的丢失
      

        collectionContainer = UIView(frame: .zero)
        self.addSubview(collectionContainer)
        
        collectionContainer.snp.makeConstraints { (make) in
             make.top.equalTo(contentLable.snp.bottom).offset(10)
       make.bottom.equalTo(self).offset(-5)
             make.left.equalTo(contentLable)
             make.width.equalTo(Globalwidth)
//     make.height.equalTo(44)

            //从新建立约束
//     contentLable.snp.makeConstraints({ (make) in
//     make.bottom.equalTo(collectionContainer.snp.top).offset(-10)
//
//            })
        }

        
        let layout = UICollectionViewFlowLayout.init()

        layout.minimumLineSpacing = 5
        layout.minimumInteritemSpacing = 5.0
        layout.scrollDirection = .vertical
        

        imageCollection = UICollectionView(frame:.zero , collectionViewLayout: layout)
         collectionContainer.addSubview(imageCollection)
        
        imageCollection.isScrollEnabled = false//禁止滑动
        imageCollection.register(DYCollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
//        imageCollection.bounces = false//禁止弹簧效果
        imageCollection.delegate = self
        imageCollection.dataSource = self
        imageCollection.backgroundColor = UIColor.white
        imageCollection.showsHorizontalScrollIndicator = false
        imageCollection.showsVerticalScrollIndicator = false

        imageCollection.snp.makeConstraints { (make) in
            make.edges.equalTo(self.collectionContainer)
//            make.top.equalTo(contentLable.snp.bottom).offset(10)
//            make.bottom.equalTo(-5)
//            make.left.equalTo(contentLable)
//            make.right.equalTo(-10)
//            make.width.equalTo(Globalwidth)
//
        }
//        //带赞按钮
//        likebutton = UIButton()
//        self.addSubview(likebutton)
//        likebutton.setImage(UIImage(named: "点赞1.png"), for: .selected)
//        likebutton.setImage(UIImage(named: "未点赞.png"), for: .normal)
//        likebutton.addTarget(self, action: #selector(lickClick), for: .touchUpInside)
//        likebutton.snp.makeConstraints { (make) in
//            make.width.equalTo(26)
//            make.height.equalTo(28)
////    make.top.equalTo(imageCollection.snp.bottom).offset(13)
//            make.bottom.equalTo(self).offset(-11)
//            make.left.equalTo(240)
//            imageCollection.snp.makeConstraints({ (make) in
//                make.bottom.equalTo(likebutton.snp.top).offset(-13)
//            })
//        }
        //收藏
//        collectbutton = UIButton()
//        self.addSubview(collectbutton)
//        collectbutton.setImage(UIImage(named: "收藏.png"), for: .normal)
//        collectbutton.snp.makeConstraints { (make) in
//            make.width.height.equalTo(likebutton)
//            make.bottom.equalTo(likebutton)
//            make.left.equalTo(likebutton.snp.right).offset(21)
//        }
//       //转发
//        transmitbutton = UIButton()
//        self.addSubview(transmitbutton)
//        transmitbutton.setImage(UIImage(named: "转发.png"), for: .normal)
//        transmitbutton.snp.makeConstraints { (make) in
//            make.width.height.equalTo(collectbutton)
//            make.bottom.equalTo(collectbutton)
//            make.left.equalTo(collectbutton.snp.right).offset(21)
//        }
//        creatattention()
    }
    
//    func creatattention(){
//        attention = UIButton()
//        self.addSubview(attention)
//        attention.setImage(UIImage(named: "关注.png"), for: .normal)
//        attention.addTarget(self, action: #selector(guanzhu), for: .touchUpInside)
//        attention.snp.makeConstraints { (make) in
//            make.top.equalTo(16)
//            make.right.equalTo(-14)
//            make.width.equalTo(50)
//            make.height.equalTo(30)
//        }
//    }

    //返回1个分区
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    //设置每个分区的item的个数
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    

    //设置collectionView的cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! DYCollectionViewCell
    
        let url = URL(string:"\(domainName)"+images[indexPath.row] )
    
        
//        do {
//            let data = try Data(contentsOf: url!)
//            cell.dyimageview.image = UIImage(data: data)
//
//        }catch let error as NSError {
//            print("内容图片错误信息",error)
//        }
        
        cell.dyimageview.setImageWith( url!, placeholderImage: UIImage(named: "photo.jpg"))//使用第三方库加载网络图片
        if images.count == 1 {
            cell.dyimageview.layer.masksToBounds = true
            cell.dyimageview.layer.cornerRadius = 14
        }
//加载图片
      return cell
    }


    //图片的点击事件
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        print("图片地址",images)
        
        for index in 0..<images.count{
            let url = URL(string:images[index] )
            SDWebImageDownloader.shared.downloadImage(with: url, options: SDWebImageDownloaderOptions.highPriority, progress: nil) { (image, data, error, finished) in

                if(self.imagedetails.count < self.images.count){
                self.imagedetails.append(image!)
                }
                
                if(self.imagedetails.count == self.images.count ){
                    
                    let blowse: ImgCollectionViewController = ImgCollectionViewController()
                    blowse.currentIndexPath = indexPath
                    blowse.imageArray = self.imagedetails
                    self.tiao.JumpPictureDetailsCell(vc: blowse)
                }
            }//异步下载图片//跳转到图片详情
        }
        

      
    }
    
    //根据图片的个数设置t单元格的大小和行间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        if (images.count == 1){
            layoutsize = CGSize(width: 350, height: 150)
            
        }
        
        if (images.count > 1 && images.count <= 4){
            layoutsize =  CGSize(width:170, height:150)
        }

        if (images.count > 4){
            layoutsize =  CGSize(width:110, height:100)
       
        }

        print(layoutsize)
        
        return layoutsize
        
    }

    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        if (images.count > 1 && images.count <= 4){
            layoutInsets = UIEdgeInsets(top: 5, left:5, bottom:5, right: 23)
        }

        if (images.count > 4){
           layoutInsets = UIEdgeInsets(top: 5, left:5, bottom:5, right: 23)
        }

//        print(layoutInsets)

        //做imageas为空的处理
        if(images.count == 0){
            layoutInsets = UIEdgeInsets(top: 5, left:5, bottom:5, right: 30)
        }
        if(images.count == 1){
            layoutInsets = UIEdgeInsets(top: 5, left:70, bottom:5, right: 90)
        }
        return layoutInsets
    }

//s关注点击事件
    @objc func guanzhu(sender:UIButton){
        
        sender.isUserInteractionEnabled = false //取消点击效果
        attention.snp.makeConstraints { (make) in
        
                make.width.equalTo(55)
        }
       attention.setTitle(" √ 已关注", for: .normal)
       attention.setTitleColor( UIColor(displayP3Red: 192/255, green: 192/255, blue: 192/255, alpha: 1), for: .normal)
        attention.layer.borderColor = UIColor(displayP3Red: 192/255, green: 192/255, blue: 192/255, alpha: 1).cgColor

        print("点击")
    }
    
    @objc func lickClick(sender:UIButton){
        
     sender.isSelected = !sender.isSelected
     Selectedbool = sender.isSelected
        
        if Selectedbool {
            UserDefaults.standard.set("like", forKey: "likebutton")
            UserDefaults.standard.synchronize()
        
        }else{
            UserDefaults.standard.set("notlike", forKey: "likebutton")
            UserDefaults.standard.synchronize()
        }
        print("dianji")
    
    }
    
    //动态设置行高的方法
    func getLabHeigh(labelStr:String,font:UIFont,width:CGFloat,lineSpacing:CGFloat=0) -> CGFloat {
        let statusLabelText: NSString = labelStr as NSString
        let size = CGSize(width: width, height: 9999)
        //通过富文本来设置行间距
        let paraph = NSMutableParagraphStyle()
        //行间距设置
        paraph.lineSpacing = lineSpacing
        //样式属性集合
        let attributes = [NSAttributedString.Key.font:font,NSAttributedString.Key.paragraphStyle: paraph]
        //boundingRect函数只有NSString可以用
        let strSize = statusLabelText.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        return strSize.height
        
    }  
}


